/* ----------------------------------------------------------------------
 *	Shadow Quest
 *	Copyright (C) 2009 Prageeth Silva <prageeth@thenewcoders.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *  ----------------------------------------------------------------------
 */

package sq;

import java.util.ArrayList;

import org.keplerproject.luajava.LuaState;
import org.keplerproject.luajava.LuaStateFactory;
import org.newdawn.slick.Input;

public class LoadScript 
{
	
	private static final String FUNC_UPDATE = "update";
	private LuaState luaState;

	/**
	* Constructor
	* @param fileName File name with Lua script.
	*/
	public LoadScript(final String fileName) 
	{
		this.luaState = LuaStateFactory.newLuaState();
		this.luaState.openLibs();
		this.luaState.LdoFile(fileName);
	}
	
	/**
	* Ends the use of Lua environment.
	*/
	public void closeScript()
	{
		this.luaState.close();
	}
	
	/**
	* Call a Lua function inside the Lua script to insert
	* data into a Java object passed as parameter
	* @param functionName Name of Lua function.
	* @param obj A Java object.
	*/
	public void runScriptFunction(String functionName, Object obj)
	{
		this.luaState.getGlobal(functionName);
		this.luaState.pushJavaObject(obj);
		this.luaState.call(1, 0);
	}
	
	/**
	* Call the Create Lua function inside the Lua script.
	* @param obj A Java object.
	* @param width The width as a Java object.
	* @param height The height as a Java object.
	*/
	public void runScriptFunction(String functionName, ArrayList<Object> objs)
	{
		this.luaState.getGlobal(functionName);
		for (Object o: objs)
		{
			this.luaState.pushJavaObject(o);
		}
		this.luaState.call(objs.size(), 0);
	}
	
	/**
	* Call the Create Lua function inside the Lua script.
	* @param obj A Java object.
	* @param width The width as a Java object.
	* @param height The height as a Java object.
	*/
	// TODO remove
	public void runUpdateScriptFunction(Object obj, Input input, Integer delta)
	{
		this.luaState.getGlobal(LoadScript.FUNC_UPDATE);
		this.luaState.pushJavaObject(obj);
		this.luaState.pushJavaObject(input);
		this.luaState.pushJavaObject(delta);
		this.luaState.call(3, 0);
	}
	
}